package com.design.iterator;

import java.util.List;

/**
 * @author leali
 * @title: ProductIterator
 * @projectName design
 * @description: 商品迭代器：具体迭代器
 * @date 2022/1/3 19:22
 */
public class ProductIterator implements AbstractIterator {
    private final List<String> products;
    /**
     * 定义一个游标，用于记录正向遍历的位置
     */
    private int cursorNext;
    /**
     * 定义一个游标，用于记录逆向遍历的位置
     */
    private int cursorPrev;

    public ProductIterator(ProductList productList) {
        //获取集合对象
        this.products = productList.getObjects();
        //设置正向遍历游标的初始值
        cursorNext = 0;
        //设置逆向遍历游标的初始值
        cursorPrev = products.size() - 1;
    }

    @Override
    public void next() {
        if (cursorNext < products.size()) {
            cursorNext++;
        }
    }

    @Override
    public boolean isLast() {
        return cursorNext == products.size();
    }

    @Override
    public void previous() {
        if (cursorPrev > -1) {
            cursorPrev--;
        }
    }

    @Override
    public boolean isFirst() {
        return cursorPrev == -1;
    }

    @Override
    public Object getNextItem() {
        return products.get(cursorNext);
    }

    @Override
    public Object getPreviousItem() {
        return products.get(cursorPrev);
    }
}
